/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import com.hiddenequity.conversion_service.ConversionService;
import com.hiddenequity.conversion_service.ConversionResponseParser;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.DataValidator;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.ViewStub;
import android.widget.EditText;

public class Act_ConversionOperation extends Act_Super{
	
	private String conversionId;
	private String conversionName;
	
	
	private EditText edit_conversion_name;
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.super_operation_layout);

		((ViewStub) findViewById(R.id.stub_conversion_operation)).inflate();
        
        title.setText(getString(R.string.title_conversion_add));
        sub_title.setVisibility(View.GONE);
        filter.setVisibility(View.GONE);
        
        Intent intent = getIntent();
        conversionId = intent.getStringExtra("conversionId");
        conversionName = intent.getStringExtra("conversionName");
        
        
        edit_conversion_name = (EditText) findViewById(R.id.edit_conversion_name);
        
        if(conversionId != null && conversionName != null)
        	setUpForm();
        
    }//onCreate
    
    
    
    /*
     * Setting up the form
     */
    private void setUpForm() {
    	edit_conversion_name.setText(conversionName);
	}//setUpForm

	/*
     * Add campaign (button onClick handler)
     */
    public void onClick_saveData(View v){
    	if(isDataValid()){
    		runOperationAsync(OPERATION_SET_DATA, getString(R.string.progress_saving), false);
    	} else {
    		showOperationError(R.string.msg_title_invalid_data, formErrorString);
    	}
    }//onClick_addAdGroup
    
 
    
    /*
     * Collecting and validating form data
     */
    //private String conversionName;
    //private boolean conversionLocation;

    private boolean isDataValid(){
    	boolean result = true;

    	conversionName = edit_conversion_name.getText().toString();
    	
    	if(!DataValidator.isName(conversionName)){
    		result = false;
    		formErrorString = getString(R.string.msg_invalid_conversion_name);
    	}
    		
    	return result;
    }//isDataValid
    
    
    /*
     * Conversion Operation
     */
	protected void conversionOperation() {
		String resp = Communication.postSOAP(
				ConversionService .URL_CONVERSION_SERVICE, 
				ConversionService.addConversionTracker(conversionId, conversionName)
    		);

    	ConversionResponseParser campaignParser = new ConversionResponseParser(resp);
    	
    	responseErrorString = campaignParser.checkForErrors();
	}
    
    
	/*
	 * Async operation
	 */
	private void runOperationAsync(final int operation, String message, boolean overlap) {

		// Stop if thread is alive
		if (thread.isAlive() && !overlap)
			return;

		// Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		// Check if Internet connection alive
		if (!isConnectionAvalable()) {
			progressDialog.dismiss();
			return;
		}

		thread = new Thread() {
			public void run() {
				// Perform authentication
				new AuthService(Act_ConversionOperation.this, getApplication());

				// Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
						case OPERATION_GET_DATA:
							//Act_ConversionOperation.this.getAdGroupData();
							break;

						case OPERATION_SET_DATA:
							Act_ConversionOperation.this.conversionOperation();
							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				// Perform postoperation
				Act_ConversionOperation.this.runOnUiThread(new Runnable() {
					public void run() {

						progressDialog.dismiss();

						if (AuthService.authToken != null) {

							showOperationError(R.string.msg_title_error,
									responseErrorString);

							switch (operation) {
							case OPERATION_GET_DATA:
								//setUpForm();
								break;

							case OPERATION_SET_DATA:
								if (responseErrorString == null)
									finishActivityWithResult(RESPONSE_REFRESH_REQUIRED);
								break;
							}

						} else {
							Intent intent = new Intent(
									Act_ConversionOperation.this
											.getApplicationContext(),
									Act_Login.class);
							startActivityForResult(intent,
									REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start();

	}//runOperationAsync
  
}
